package com.fengmi.interceptor;

import cn.hutool.json.JSONUtil;
import com.fengmi.sso.entity.SysUser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    private static ThreadLocal<SysUser> local = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

       //从请求头中获取用户信息
        String sysUserJson = request.getHeader("userinfo");

        if(!StringUtils.isEmpty(sysUserJson)){
            SysUser sysUser = JSONUtil.toBean(sysUserJson, SysUser.class);

            //将用户信息存放在threadlocal中
            local.set(sysUser);
        }

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        local.remove();
    }


    public static SysUser getUserInfo(){
        return local.get();
    }
}
